<script setup lang="ts">
import {
  mdiChevronDown,
  mdiChevronUp,
  mdiCloseBoxMultiple,
  mdiCloseCircle,
  mdiFormatListBulleted,
  mdiOpenInNew,
  mdiUngroup
} from '@mdi/js'
import { useI18n } from 'vue-i18n'
import { useLayoutStore } from '@/windows/layoutBrowser/stores/layout'
import {
  calculateMouseDistanceToElement,
  handleResolvedDrop,
  resolveBrowserTabOrGroup
} from '@/composables/dragAndDrop/dragDropUtil'
import { useDragHandle } from '@/composables/dragAndDrop/useDragHandle'
import { useDropHandle } from '@/composables/dragAndDrop/useDropHandle'
import { showContextMenu } from '@/utils/contextMenuHelper'
import DropIndicator from '@/windows/layoutBrowser/components/common/DropIndicator.vue'
import { useTabStore } from '@/windows/layoutBrowser/stores/tab'
import { TAB_MARGIN, useTabWidthStore } from '@/windows/layoutBrowser/stores/tabWidth'

const props = defineProps<{
  tab: F2.tab.Group
}>()

const tabElementRef = ref<HTMLElement>()
const dragHandleRef = ref<HTMLElement>()
const tabWidthStore = useTabWidthStore()

useDragHandle<F2.tab.Group>({
  el: tabElementRef,
  dragEl: dragHandleRef,
  nativeDrag: true,
  dragData: props.tab,
  dragType: 'browser-tab-group'
})

const { dropState } = useDropHandle({
  el: tabElementRef,
  acceptedTypes: ['browser-tab', 'browser-tab-group'],
  allowedEdges: ['left', 'right'],
  canDrop(source, input) {
    const boundary = tabWidthStore.dragBoundary
    // 分组不允许嵌套
    if (!tabElementRef.value) {
      return false
    }
    // 检查分组的拖拽边界限制
    const distance = calculateMouseDistanceToElement(input, tabElementRef.value)
    return !(
      source['browser-tab'] !== undefined &&
      distance.left >= boundary.leftMin &&
      distance.right >= boundary.rightMin
    )
  },
  onDrop(source, edge, isExternal) {
    const resolved = resolveBrowserTabOrGroup(source)
    handleResolvedDrop(
      resolved,
      props.tab.id,
      edge === 'right',
      isExternal,
      tabStore.moveTabRelativeToAnother
    )
  }
})

const tabStore = useTabStore()
const layoutStore = useLayoutStore()

// 是否已为当前分组打开“分组详情”抽屉
const isInspectorOpen = computed(() => {
  return layoutStore.showGroupDrawer && layoutStore.groupParams?.groupId === props.tab.id
})

// 切换当前分组“分组详情”抽屉显示/隐藏
function onToggleGroupInspector() {
  if (isInspectorOpen.value) {
    layoutStore.closeGroupInspector()
  } else {
    layoutStore.showGroupInspector(props.tab.id)
  }
}

/**
 * 切换分组展开/收缩状态
 */
function toggleGroupCollapsed(groupId: number) {
  const group = tabStore.tabs.find(item => 'tabs' in item && item.id === groupId) as F2.tab.Group
  if (group) {
    group.collapsed = !group.collapsed
  }
}

// 右键菜单
const { t } = useI18n()

/**
 * 显示分组右键菜单（使用composable）
 */
async function showGroupContextMenu(event: MouseEvent, group: F2.tab.Group) {
  event.preventDefault()
  event.stopPropagation()

  await showContextMenu([
    {
      label: `${t('group.contextMenu.inspect')} (&V)(V)`,
      icon: mdiFormatListBulleted,
      cb: () => {
        layoutStore.showGroupInspector(group.id)
      }
    },

    {
      label: `${t('group.contextMenu.openInNewWindow')} (&N)(N)`,
      icon: mdiOpenInNew,
      cb: () => {
        // 获取分组中所有标签页的ID
        const tabIds = group.tabs.map(tab => tab.id)
        _pre_.browser.create(tabIds)
      }
    },
    {
      label: `${t('group.contextMenu.ungroup')} (&U)(U)`,
      icon: mdiUngroup,
      cb: () => {
        tabStore.removeTabsFromGroup(
          group.id,
          group.tabs.map(tab => tab.id)
        )
      }
    },
    { type: 'separator' },
    {
      label: `${t('group.contextMenu.closeGroup')} (&G)(G)`,
      icon: mdiCloseCircle,
      cb: () => {
        group.waitingTabs = []
        tabStore.closeTabs(group.tabs.map(tab => tab.id))
      }
    },
    {
      label: `${t('group.contextMenu.closeAll')} (&A)(A)`,
      icon: mdiCloseBoxMultiple,
      cb: () => tabStore.closeAllTabs()
    }
  ])
}

// ==================== 分组功能 ====================
/**
 * 计算分组内容的动态样式（增强版）
 */
function getGroupContentStyleEnhanced(group: F2.tab.Group) {
  if (group.collapsed) {
    return {
      maxWidth: '0px',
      opacity: 0,
      transform: 'scaleX(0)'
    }
  } else {
    // 如果有正在删除的tab，使用当前宽度避免动画冲突
    const tabCount = group.tabs.length + group.waitingTabs.length

    const tabWidthWithMargin = tabWidthStore.tabWidth + TAB_MARGIN
    const calculatedWidth = tabCount * tabWidthWithMargin
    return {
      maxWidth: `${calculatedWidth}px`,
      opacity: 1,
      transform: 'scaleX(1)'
    }
  }
}
</script>

<template>
  <div ref="tabElementRef" class="tab-group d-flex align-center rounded ml-1 position-relative">
    <div
      ref="dragHandleRef"
      class="tab-group-header text-center rounded cursor-pointer"
      :data-testid="`group-${tab.id}`"
      :style="{
        background: tab.color
      }"
      @click="toggleGroupCollapsed(tab.id)"
      @contextmenu.prevent="event => showGroupContextMenu(event, tab)"
    >
      <span class="text-caption text-white">{{ tab.tabs.length }}</span>
    </div>
    <v-btn
      class="ml-1"
      color=""
      :data-testid="`group-compact-btn-${tab.id}`"
      density="compact"
      :icon="isInspectorOpen ? mdiChevronUp : mdiChevronDown"
      size="small"
      variant="text"
      @click.stop="onToggleGroupInspector"
      @contextmenu.prevent="(event: MouseEvent) => showGroupContextMenu(event, tab)"
    />

    <div
      class="tab-group-content"
      :style="{
        borderTop: `1px solid ${tab.color}`,
        ...getGroupContentStyleEnhanced(tab)
      }"
    >
      <v-slide-y-reverse-transition group hide-on-leave origin="center top">
        <slot v-for="ta in tab.tabs" :key="ta.id" name="tab-item" :tab="ta"></slot>
        <slot v-for="ta in tab.waitingTabs" :key="ta.id" name="waiting-tab-item" :tab="ta"></slot>
      </v-slide-y-reverse-transition>
    </div>
    <DropIndicator
      v-if="dropState.type === 'drag-over' && dropState.closestEdge"
      :edge="dropState.closestEdge"
      offset="-3px"
    ></DropIndicator>
  </div>
</template>

<style scoped>
/* ==================== 分组样式 ==================== */
.tab-group {
  padding: 0 3px 0 3px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.tab-group-header {
  width: 24px;
  height: 22px;
  user-select: none;
}

.tab-group-header:hover {
  opacity: 0.8;
}

.cursor-pointer {
  cursor: pointer;
}

.tab-group-content {
  display: flex;
  align-items: center;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: left center;
  padding-top: 3px;
}

.tab-group.slide-y-reverse-transition-move {
  transition: all 0.2s !important;
}
</style>

<i18n>
{
  "zhHans": {
    "group": {
      "contextMenu": {
        "expand": "展开分组",
        "collapse": "收缩分组",
        "inspect": "查看分组详情",
        "inspectTitlePrefix": "分组详情",
        "openInNewWindow": "在新窗口打开",
        "ungroup": "取消分组",
        "closeGroup": "关闭分组",
        "closeAll": "关闭所有页面"
      },
      "message": {
        "clearedWaiting": "已清空 {count} 个等待中的标签"
      }
    }
  },
  "en": {
    "group": {
      "contextMenu": {
        "expand": "Expand Group",
        "collapse": "Collapse Group",
        "inspect": "Inspect Group",
        "inspectTitlePrefix": "Group Detail",
        "openInNewWindow": "Open in New Window",
        "ungroup": "Ungroup Tabs",
        "closeGroup": "Close Group",
        "closeAll": "Close All Tabs"
      },
      "message": {
        "clearedWaiting": "Cleared {count} waiting tabs"
      }
    }
  }
}
</i18n>
